﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Web.Admin.Services.Sites;
using SaaS.Model.Entity.Sites;
using SaaS.Model.Enums;

namespace Web.Admin.Controllers.Sites
{
    [Route("api/[controller]")]
    [ApiController]
    public class AdminController : AdminControllerBase
    {
        private readonly AdminAppService _adminAppService;
        public AdminController(AdminAppService adminAppService)
        {
            _adminAppService = adminAppService;
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult List()
        {
            IQueryable<SiteAdmin> query = ADC.SiteAdmins.Where(c => c.SiteId == Session.SiteId);
            return PageResult(query.OrderByDescending(c => c.CreationTime), c => new
            {
                c.Id,
                c.UserName,
                c.IsDefault,
                c.InitPassword,
                c.IP,
                c.RoleId,
                c.Status,
                c.CreationTime
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="username"></param>
        /// <param name="roleId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(int? id, string username, int roleId, UserStatus? status)
        {
            return Ok(_adminAppService.CreateOrEdit(id ?? 0, username, roleId, status ?? UserStatus.Normal));
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public ActionResult Delete(int id)
        {
            return Ok(_adminAppService.Delete(id));
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Info(int id)
        {
            SiteAdmin admin = ADC.SiteAdmins.Where(c => c.Id == id && c.SiteId == Session.SiteId).FirstOrDefault();
            if (admin == null) throw new AdminException("管理员不存在", AdminLoggerSource.Admin);
            return Ok(new
            {
                admin.UserName,
                admin.Status,
                admin.Id,
                admin.IsDefault,
                admin.RoleId,
                admin.SiteId
            });
        }
    }
}